﻿using System;

namespace ECommerce.Administration.Controls
{
	public partial class AdminHeaderMenu : AdminBaseUsercontrol
	{
		#region Handlers
		protected override void OnPreRender(EventArgs e)
		{
			System.Web.SiteMapProvider siteMapProvider = System.Web.SiteMap.Providers[SiteMapProviderName];
			if (siteMapProvider == null)
			{
				Visible = false;
			}
			else
			{
				var sb = new System.Text.StringBuilder();
				sb.AppendFormat("<ul id=\"{0}\" class=\"sf-menu\">", ClientID);
				foreach (System.Web.SiteMapNode node in siteMapProvider.RootNode.ChildNodes)
				{
					BuildMenuRecursive(sb, node);
				}
				sb.Append("</ul>");
				lblMenuContent.Text = sb.ToString();
			}

			string superFishMenu = CommonHelper.GetStoreLocation() + "Scripts/jquery.superfishmenu.js";
			Page.ClientScript.RegisterClientScriptInclude(superFishMenu, superFishMenu);
			Page.ClientScript.RegisterClientScriptBlock(GetType(), String.Format("{0}_sfmenu", ClientID), String.Format("$(document).ready(function(){{$('#{0}').superfish({{autoArrows:false,speed:'fast',delay:200}});}});", ClientID), true);
		}

		protected void Page_Load(object sender, EventArgs e)
		{
		}
		#endregion

		#region Utilities
		private void BuildMenuRecursive(System.Text.StringBuilder sb, System.Web.SiteMapNode node)
		{
			string title = System.Web.HttpUtility.HtmlEncode(GetLocalResourceString(node["ResourceTitle"]));
			//string descr = System.Web.HttpUtility.HtmlEncode(!String.IsNullOrEmpty(node["ResourceDescription"]) ? GetLocalResourceString(node["ResourceDescription"]) : node.Description);

			sb.Append("<li>");
			sb.AppendFormat("<a href=\"{0}\">{1}</a>", (String.IsNullOrEmpty(node.Url) ? "#" : node.Url), title);
			if(node.HasChildNodes)
			{
				sb.Append("<ul>");
				foreach(System.Web.SiteMapNode childNode in node.ChildNodes)
				{
					BuildMenuRecursive(sb, childNode);
				}
				sb.Append("</ul>");
			}
			sb.Append("</li>");
		}
		#endregion

		#region Properties
		public string SiteMapProviderName
		{
			get
			{
				return Convert.ToString(ViewState["SiteMapProviderName"]);
			}
			set
			{
				ViewState["SiteMapProviderName"] = value;
			}
		}
		#endregion
	}
}